package com.dx.core.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.List;

/**
 * 通用配置文件单独加载地址
 *
 * @author xufeng
 * @since 14.04.2023
 */
public class CommonConfigEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        try {
            Resource[] resources = new PathMatchingResourcePatternResolver()
                    .getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "config/*.yml");

            for (Resource resource : resources) {
                List<PropertySource<?>> configs = loader.load(resource.getFilename(), resource);
                if (configs != null && !configs.isEmpty()) {
                    environment.getPropertySources().addLast(configs.get(0));
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
